package org.example.work2.tcc.account.service.impl;

import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.example.work2.tcc.account.dto.Account;
import org.example.work2.tcc.account.mapper.AccountMapper;
import org.example.work2.tcc.account.service.AccountAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AccountActionImpl implements AccountAction {

	@Autowired
	private AccountMapper accountMapper;

	@Override
	public Account findAccountByCode(String accountCode) {
		return accountMapper.findAccountByCode(accountCode);
	}

	@Override
	@Transactional
	public boolean updateScoresPrepare(BusinessActionContext actionContext, String accountCode, Integer frozenScores) throws Exception {

		log.info("[updateScoresPrepare] 当前 XID: {}", RootContext.getXID());
		log.info("[updateScoresPrepare] 开始更新用户:{} 设置冻结积分为：{}", accountCode, frozenScores);
		// 扣除积分
		Account account = new Account();
		account.setAccountCode(accountCode);
		account.setFrozenScores(frozenScores);
		int updateCount = accountMapper.updateScores(account);
		// 扣除成功
		if (updateCount <= 0) {
			throw new Exception("[updateScoresPrepare] 更新用户冻结积分失败");
		}
		log.info("[updateScoresPrepare] 更新用户冻结积分成功");
		return true;
	}

	private Account buildAccountFromActionContext(BusinessActionContext actionContext){
		String accountCode = (String)actionContext.getActionContext("accountCode");
		Integer frozenScores = (Integer)actionContext.getActionContext("frozenScores");
		Account account = new Account();
		account.setAccountCode(accountCode);
		account.setFrozenScores(frozenScores);
		return account;
	}

	@Override
	@Transactional
	public boolean updateScoresCommit(BusinessActionContext actionContext) throws Exception {
		log.info("[updateScoresCommit] 当前 XID: {}", actionContext.getXid());
		int flag = accountMapper.updateScoresCommit(buildAccountFromActionContext(actionContext));
		if(flag <= 0){
			throw new Exception("[updateScoresCommit] 失败");
		}
		log.info("[updateScoresCommit] 成功");
		return true;
	}

	@Override
	@Transactional
	public boolean updateScoresRollBack(BusinessActionContext actionContext) throws Exception {
		log.info("[updateScoresRollBack] 当前 XID: {}", actionContext.getXid());
		int flag = accountMapper.updateScoresRollBack(buildAccountFromActionContext(actionContext));
		if(flag <= 0){
			throw new Exception("[updateScoresRollBack] 失败");
		}
		log.info("[updateScoresRollBack] 成功");
		return true;
	}

}
